package com.itheima.controller;


import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

//注意回调方法与原始方法的返回值要一样，不然报错*************
    @RequestMapping("/{id}")
    @HystrixCommand
    public String queryById(@PathVariable Long id){
//        原始方式调用
//                String url="";
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;
//        User user = restTemplate.getForObject(url, User.class);
        //获取eureka中注册的user-service的实例

//        负载均衡下使用 ribbun

        //模拟触发熔断
        if(id==1){
            throw new RuntimeException("太忙了");
        }

        String url="";
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = serviceInstances.get(0);
        url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url, String.class);

    }

    public String queryByIdFallBacks(@PathVariable  Long id){
        log.error("失败的消息 id:{}",id);
        return "网络拥挤";
    }
    public String defaultFallback(){
        return "对不起，服务器太拥挤了！";
    }
}
